import { UserState } from '@/store/interface'
import { login, getInfo, logout } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import piniaPersistConfig from '@/config/piniaPersist'
import defAva from '@/assets/images/avatar.jpg'

export const useUserStore = defineStore({
  id: 'user',
  state: (): UserState => ({
    token: getToken() || '',
    id: '',
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
    userInfo: {}
  }),
  actions: {
    login(userInfo: any) {
      console.log('登录', userInfo)
      const username = userInfo.username
      const password = userInfo.password
      return new Promise((resolve: any, reject: any) => {
        login(username, password)
          .then((res: any) => {
            // console.log('有无token',res)
            setToken(res.data.token)
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },

    getInfo() {
      // console.log('为啥打印不出')
      return new Promise((resolve: any, reject: any) => {
        getInfo().then((res: any) => {
            const user = res.user
            const avatar = user.avatar == '' || user.avatar == null ? defAva : import.meta.env.VITE_APP_BASE_API + user.avatar   
            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.id = user.userId
            this.name = user.userName
            this.avatar = avatar
            resolve(res)
          }).catch((err) => {
            reject(err)
          })
      })
    },

     // 退出系统
     logOut() {
      return new Promise((resolve, reject) => {
        logout().then((res:any) => {
          this.token = ''
          this.userInfo = {}
          removeToken()
          resolve(res.data)
        }).catch(error => {
          reject(error)
        })
      })
    }
    
  },
  persist: piniaPersistConfig('user')
})
